package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author 课工场
 * @date 2024/12/6
 * @description   演示shiro授权方式
 *  1.当用户访问受限资源时  授权器会自动调用自定义Realm中的授权方法doGetAuthorizationInfo
 *  2. 如何标识资源时受限资源
 *    2.1 编程式
 *    2.2 注解式  常用
 *          基于角色的权限控制
 *          基于字符串的权限控制
 *
 *  /user/add     role  ->   admin   sys:user:add   sys:user:update  sys:user:delete
 */
public class TestAuthorization {


    public static void main(String[] args) {

        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        CustomerRealm realm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        realm.setCredentialsMatcher(md5);
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("root", "123456");
        subject.login(usernamePasswordToken);
        System.out.println("subject.isAuthenticated() = " + subject.isAuthenticated());

        // 判定用户是否拥有某种权限  角色
        // boolean b = subject.hasRole("super");
        // boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "super", "customer"));
        // for (boolean aBoolean : booleans) {
        //     System.out.println("aBoolean = " + aBoolean);
        // }

        // boolean b = subject.hasAllRoles(Arrays.asList("admin", "super"));
        // System.out.println("'b' = " + b);


        // 基于权限字符串判定
        boolean permitted = subject.isPermitted("sys:user:add");
        System.out.println("permitted = " + permitted);
    }


}
